/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package resources;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Christoph
 */
public class ResourceManager {

    static final private String APPNAME = "MyTracks";
    static final private String PROPERTYNAME = APPNAME + ".properties";
    static final private String DATABASEFOLDERNAME = "Database";
    static final private String MULTIMEDIAFOLDERNAME = "MultiMedia";
    static final private String HELPFOLDERNAME = "Help";
    static final private String GPXFILESFOLDERNAME = "GPX-Files";
    static final public String DATABASE_PATH = "DBPath";
    static final public String MULTIMEDIA_PATH = "MMPATH";
    static final public String HELP_PATH = "HELPPATH";
    static final public String GPX_PATH = "GPXPATH";
    private String homePath;
    private String propertyPath;
    private String dataBasePath;
    private String mmFolderPath;
    private String gpxFolderPath;
    private String helpFolderPath;

    /**
     * Constructor
     */
    public ResourceManager() {

        detectHomePath();
        createFolders();

    }

    /**
     * Erzeugt Ordner in dem die Dateien, die das Programm benutz gespeichert
     * werden und schreibt die benoetigten Pfrade in die properties
     */
    private void createFolders() {


        //Erstelle Ordner
        File myTracks = new File(homePath + File.separator + APPNAME);
        myTracks.mkdir();

        dataBasePath = homePath + File.separator + APPNAME + File.separator + DATABASEFOLDERNAME;
        File dbFolder = new File(dataBasePath);
        dbFolder.mkdir();

        mmFolderPath = homePath + File.separator + APPNAME + File.separator + MULTIMEDIAFOLDERNAME;
        File mmFolder = new File(mmFolderPath);
        mmFolder.mkdir();
        
        helpFolderPath = homePath + File.separator + APPNAME + File.separator + HELPFOLDERNAME;
        File helpFolder = new File(helpFolderPath);
        helpFolder.mkdir();

        gpxFolderPath = homePath + File.separator + APPNAME + File.separator + GPXFILESFOLDERNAME;
        File gpxFolder = new File(gpxFolderPath);
        gpxFolder.mkdir();

        //Prüft ob die Property Datei schon existiert
        propertyPath = homePath + File.separator + APPNAME + File.separator + PROPERTYNAME;
        File propFile = new File(propertyPath);
        if (!propFile.exists()) {


            try {
                //legt Property Datei an und setzt Werte
                Properties props = new Properties();
                props.setProperty(DATABASE_PATH, dataBasePath);
                props.setProperty(MULTIMEDIA_PATH, mmFolderPath);
                props.setProperty(HELP_PATH, helpFolderPath);
                props.setProperty(GPX_PATH, gpxFolderPath);
                FileOutputStream out = new FileOutputStream(propertyPath);
                props.store(out, null);




            } catch (FileNotFoundException ex) {
                Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
            }



        }


        // liest die Property Datei aus und gibt die Werte aus
        // zu Testzwecken
        try {
            Properties props = new Properties();
            FileInputStream in = new FileInputStream(propertyPath);
            props.load(in);
            in.close();
            StringBuilder str = new StringBuilder();
            str.append(props.getProperty(DATABASE_PATH)).append("\n");
            str.append(props.getProperty(MULTIMEDIA_PATH)).append("\n");
            str.append(props.getProperty(HELP_PATH)).append("\n");
            str.append(props.getProperty(GPX_PATH)).append("\n");

            System.out.println(str.toString());
        } catch (IOException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }




    }

    /**
     *
     * @return prpertyPath Gibt den Pfad der property datei zurück
     */
    private String getPropertyPath() {

        return propertyPath;
    }

    /**
     *
     * @return homePath gibt den Pfad des Home-Verzeichnises zurück
     */
    public String getHomePath() {
        return homePath;
    }

    /**
     * Ermitelt den Pfad des Home-Verzeichnises
     */
    public void detectHomePath() {


        Properties p = System.getProperties();
        homePath = p.getProperty("user.home");
        System.out.println("Home-Verzeichnis: " + homePath);

    }

    public String getProperty(String propertyKey) {

        String propValue = null;

        try {
            Properties props = new Properties();
            FileInputStream in = new FileInputStream(propertyPath);
            props.load(in);
            in.close();
            propValue = props.getProperty(propertyKey);


            System.out.println(propValue);
        } catch (IOException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (propValue == null) {
            propValue = "wrong propKey";
        }

        return propValue;

    }
    
    private void copyResourceToProperties(String resource, String newPath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(newPath)));
        
        BufferedInputStream bis = new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(resource));
        
        try {
            int b = -1;

            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
        }
        finally {
            bis.close();
            bos.flush();
            bos.close();
        }
    }
    
    public URI copyHelp() throws IOException {
        File index = new File(helpFolderPath + File.separator + "index.html");
        if (!(index.exists())) {
            //help doesnt already exist
            String helpfolder = helpFolderPath + File.separator;
            
            copyResourceToProperties("help/DeleteTrack.html", helpfolder + "DeleteTrack.html");
            copyResourceToProperties("help/addEvent.png", helpfolder + "addEvent.png");
            copyResourceToProperties("help/addEvent2.png", helpfolder + "addEvent2.png");
            copyResourceToProperties("help/addEvent3.png", helpfolder + "addEvent3.png");
            copyResourceToProperties("help/addTrack.html", helpfolder + "addTrack.html");
            copyResourceToProperties("help/deleteTrack1.png", helpfolder + "deleteTrack1.png");
            copyResourceToProperties("help/deleteTrack2.png", helpfolder + "deleteTrack2.png");
            copyResourceToProperties("help/detailansicht.png", helpfolder + "detailansicht.png");
            copyResourceToProperties("help/editTrack.html", helpfolder + "editTrack.html");
            copyResourceToProperties("help/eventDetail.png", helpfolder + "eventDetail.png");
            copyResourceToProperties("help/exportTrack.html", helpfolder + "exportTrack.html");
            copyResourceToProperties("help/hauptfenster.png", helpfolder + "hauptfenster.png");
            copyResourceToProperties("help/importTrack.html", helpfolder + "importTrack.html");
            copyResourceToProperties("help/index.html", helpfolder + "index.html");
            copyResourceToProperties("help/newTrack.png", helpfolder + "newTrack.png");
            copyResourceToProperties("help/newTrack2.png", helpfolder + "newTrack2.png");
            
        }
        
        return index.toURI();
    }
    
    private String copyToProperties(String filePath, String fileName, String fileEnding, String folderPath) {
        String newFilePath = null;
        try {
            int i = 0;
            newFilePath = folderPath + File.separator + fileName +String.valueOf(i).toString()+fileEnding;
            
            while(new File(newFilePath).exists()){
                i++;
                newFilePath = folderPath + File.separator + fileName +String.valueOf(i).toString()+fileEnding;
            }
            
            Path copySourcePath = Paths.get(filePath);
            Path copyTargetPath = Paths.get(newFilePath);
            Files.copy(copySourcePath, copyTargetPath);
        } catch (IOException ex) {
            Logger.getLogger(ResourceManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        return newFilePath;
    }

    public String copyGPXToProperties(String filePath) {
        
        return copyToProperties(filePath, "gpx_file", ".gpx", gpxFolderPath);
    }
    
    public String copyPictureToProperties(String filePath) {
        String ending = filePath.substring(filePath.lastIndexOf('.'));
        
        return copyToProperties(filePath, "picture_", ending, mmFolderPath);
    }
    
    public String copyVideoToProperties(String filePath) {
        String ending = filePath.substring(filePath.lastIndexOf('.'));
        
        return copyToProperties(filePath, "video_", ending, mmFolderPath);
    }
}
